import { Descriptions, Select, theme } from 'antd';
import type { DescriptionsItemType, DescriptionsProps } from 'antd/es/descriptions';
import cls from 'classnames';
import React, { useMemo } from 'react';
import Styles from './index.less';

const { useToken } = theme;

export const DESC_GRID_CONF = { xxl: 4, xl: 3, lg: 2, md: 2, xs: 1 };
export const GRID_CONF = { xxl: 6, xl: 8, lg: 12, md: 12, xs: 24 };

type ItemTypeProps = {
  hidden?: boolean;
  isSelect?: boolean;
  selectOptions?: { label: string; value: string | number }[];
} & DescriptionsItemType;

const BaseInfo: React.FC<
  DescriptionsProps & {
    items?: ItemTypeProps[];
    maxWidth?: number | string;
    onRunStatusChange?: (value: string | number) => void;
  }
> = ({
  items,
  maxWidth = '100%',
  column = DESC_GRID_CONF,
  labelStyle = {},
  className,
  colon = false,
  onRunStatusChange,
  ...rest
}) => {
  const { token } = useToken();
  const paddingBlock = 8;
  const _labelStyle = {
    width: 160,
    alignItems: 'center',
    justifyContent: 'flex-end',
    color: token.colorText,
    textAlign: 'right',
    ...labelStyle,
  };

  // 处理 items，确保最后一行布局正确
  const processedItems = useMemo(() => {
    if (!items?.length) return [];

    // 过滤掉隐藏的项
    const visibleItems = items.filter((item) => !item.hidden);
    const itemCount = visibleItems.length;

    // 获取当前实际的列数
    let currentColumn = 3; // 默认3列
    if (typeof column === 'number') {
      currentColumn = column;
    } else if (typeof column === 'object') {
      // 根据屏幕宽度获取响应式列数
      const screenWidth = window.innerWidth;
      if (screenWidth >= 1600) currentColumn = column.xxl || 3;
      else if (screenWidth >= 1200) currentColumn = column.xl || 3;
      else if (screenWidth >= 992) currentColumn = column.lg || 3;
      else if (screenWidth >= 768) currentColumn = column.md || 3;
      else currentColumn = column.xs || 3;
    }

    const remainder = itemCount % currentColumn;

    if (remainder === 0) return visibleItems;

    // 添加占位项使总数能被列数整除
    const paddingCount = currentColumn - remainder;
    return [
      ...visibleItems,
      ...Array(paddingCount)
        .fill(null)
        .map((_, index) => ({
          key: `padding-${index}`,
          label: '',
          children: '',
          hidden: true,
          span: 1,
        })),
    ];
  }, [items, column]);

  // 处理每个 item 的样式和内容
  const finalItems = processedItems.map((item: ItemTypeProps) => {
    let itemContentStyle = {
      margin: 0,
      background: token.colorBgContainerDisabled,
      lineHeight: 1.5,
      padding: paddingBlock,
      color: token.colorTextBase,
      minHeight: 40,
    };

    if (item.isSelect) {
      itemContentStyle.padding = 0;
    }

    if (
      (item.children === undefined || item.children === null || item.children === '') &&
      !item.hidden
    ) {
      item.children = <span>--</span>;
    }

    if (item.hidden) {
      item.style = { display: 'none' };
    }

    if (item.isSelect && item.selectOptions) {
      item.className = Styles.selectItem;
      item.children = (
        <Select
          options={item.selectOptions}
          style={{ width: '100%' }}
          value={item.children}
          onChange={(value) => {
            if (item.key === 'runStatus' && onRunStatusChange) {
              onRunStatusChange(value);
            }
          }}
        />
      );
    }

    return {
      ...item,
      contentStyle: itemContentStyle,
    };
  });

  return (
    <Descriptions
      labelStyle={_labelStyle}
      style={{ maxWidth: maxWidth }}
      className={cls(Styles.customDescriptions, className)}
      colon={colon}
      items={finalItems}
      column={column}
      {...rest}
    />
  );
};

export default BaseInfo;
